package com.quick.proxy.client;

import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.*;
import com.quick.proxy.core.utils.ByteUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * Description: 关闭代理通道
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Match(CmdTypeConstants.DISABLED_CONNECT)
@Component
@Slf4j
public class ProxyMessageDisabledConnectHandler implements ProxyMessageHandler {


    /**
     * 接收的数据帧包
     *
     * @param ctx          上下文
     * @param proxyMessage 帧报文
     */
    @Override
    public void cmdResponse(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
        String data = ByteUtils.hexToString(proxyMessage.getData());
        ForwardMessage forwardMessage = JSONUtil.toBean(data, ForwardMessage.class);
        String visitorId = forwardMessage.getVisitorId();
        Map<String, Channel> visitorIdRealProxyChannel = ctx.channel().attr(ChannelAttribute.VISITOR_ID_REAL_PROXY_CHANNEL).get();
        if (!CollectionUtils.isEmpty(visitorIdRealProxyChannel)) {
            Channel realProxyChannel = visitorIdRealProxyChannel.get(visitorId);
            if (realProxyChannel != null) {
                realProxyChannel.close();
                log.info("visitorId[{}]断开真实代理客户端", visitorId);
            }
        }
    }
}
